import json
from binance.client import Client
import math
from decimal import Decimal

# 初始化客户端
client = Client(api_key='W1Z5h7RydJ8CNI40azIXOJKVudRLfawy3k8jEdbh0sfU74yHQzVr5a78IU2E2lRV', api_secret='ZMvkc39AOccvuxLnREzFPx7UZY11grocC08qO8R1lSe7L5yGyyZyq4WlwxF0u0gr')

# 加载最小交易量数据
with open('min_trade_volumes.json', 'r') as f:
    min_trade_volumes = json.load(f)

# 获取账户信息
def get_balance(asset):
    account_info = client.get_account()
    for balance in account_info['balances']:
        if balance['asset'] == asset:
            return float(balance['free'])
    return 0.0

# 实现全仓买入
def buy_max(symbol,quote_asset):
    min_qty = min_trade_volumes[symbol]['minQuoteQty']
    quote_asset_balance = get_balance(quote_asset)
    max_qty = round(Decimal(math.floor(Decimal(quote_asset_balance) / Decimal(min_qty))) * Decimal(min_qty),8)
    order = client.order_market_buy(
        symbol=symbol,
        quoteOrderQty=max_qty
    )
    print(f"Order placed (Buy {symbol}): {order}")
    

# 实现全仓卖出
def sell_max(symbol,base_asset):
    min_qty = min_trade_volumes[symbol]['minBaseQty']
    base_asset_balance = get_balance(base_asset)
    max_qty = round(Decimal(math.floor(Decimal(base_asset_balance) / Decimal(min_qty))) * Decimal(min_qty),8)
    print(max_qty)
    order = client.order_market_sell(
        symbol=symbol,
        quantity=max_qty
    )
    print(f"Order placed (Sell {symbol}): {order}")

# 实现三步操作
def triangular_arbitrage():
    sell_max('USDTTRY','USDT')
    buy_max('IMXTRY','TRY')
    sell_max('IMXUSDT','IMX')
    
    print("Final USDT quantity: ",get_balance("USDT"))

# 执行三角套利操作
triangular_arbitrage()
